package com.mihoyo.org.service.impl;

import com.mihoyo.basic.service.impl.BaseServiceImpl;
import com.mihoyo.basic.utils.PageList;
import com.mihoyo.org.domain.Department;
import com.mihoyo.org.domain.Employee;
import com.mihoyo.org.mapper.DepartmentMapper;
import com.mihoyo.org.query.DepartmentQuery;
import com.mihoyo.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    // 部门无限级数
    @Override
    public List<Department> findDepartmentTree() {
        // 查询所有部门数据
        List<Department> all = departmentMapper.findAll();
        Map<Long, Department> deptMap = all.stream().collect(Collectors.toMap(Department::getId, Department -> Department));
        List<Department> depts = new ArrayList<>();
        for (Department dept: all) {
            if (dept.getParentId() == null) {
                depts.add(dept);
            } else {
                // 通过key 获取上级部门
                Department department = deptMap.get(dept.getParentId());
                if (department != null) {
                    department.getChildren().add(dept);
                }
            }
        }
        return depts;
    }


}
